/* eslint-disable no-tabs */
/* eslint-disable eqeqeq */
import axios from 'axios'
import router from '../router'
// import OS from "qs";

// import store from '../store';

import { Message } from 'element-ui'

// 创建axios实例
var instance = axios.create({
  timeout: 1000 * 60
})

/**
 * 发送请求拦截器
 */
instance.interceptors.request.use(
  (config) => {
    // store.commit('getToken');

    // 设置60秒超时
    // config.timeout = 60000;//设置axios请求超时时间(毫秒)

    config.headers['Content-Type'] = 'application/json;charset=utf-8'

    let userInfo = JSON.parse(window.localStorage.getItem('userInfo'))

    if (userInfo && config.url != '/hrm/login') {
      let id = userInfo.sessionId
      /*
      let session = {user_session: id};

      config.data = Object.assign(session, config.data);
      config.data = OS.stringify(config.data);
      */

      // headers 中追加 令牌信息
      config.headers['Authorization'] = id
    }

    // if (store.state.token &&
    // 	(config.url != ("/oauth/login")) &&
    // 	(config.url != ("/oauth/verificationCode"))) {

    // 	//headers 中追加 令牌信息
    // 	config.headers['Authorization'] = store.state.token;

    // }

    return config
  },
  (error) => {
    console.log('请求异常', error)

    Message.error({
      message: '服务器异常，请稍后使用！'
    })

    return Promise.reject(error)
  }
)

/**
 * 业务请求数据------响应拦截器，处理共同业务（未登录，token过期等）
 */
instance.interceptors.response.use(
  (res) => {
    // 关闭全局按钮Loading响应
    // store.dispatch('cancle_loading');

    let ret = false

    // 业务逻辑错误
    if (res.status && res.status == 200) {
      switch (res.data.code) {
        case 0:
          // 业务正常逻辑
          ret = true
          break
        case 1:
          // 验证码错误
          ret = true
          break
        case 2:
          // 参数不匹配
          ret = true
          break
        case 20001:
          // 未登录
          Message.error({
            message: res.data.msg
          })
          router.replace('/')
          return

        case 403:
          // 未授权
          Message.error({
            message: res.data.message
          })
          return

        case 500:
          // 业务逻辑或者服务器错误
          Message.error({
            message: res.data.message
          })
          return
        default:
          break
      }
    }

    if (ret) {
      // 业务正常逻辑,返回业务数据
      return res
    }
  },
  (error) => {
    if (error.response == 400 && error.response.statusText === 'Bad Request') {
      if (
        error.config.url === '/oauth/login' &&
        error.config.method === 'post'
      ) {
        Message({
          message: error.response.data.message,
          type: 'error'
        })
      }
    } else if (error.response === 403) {
      // 删除 令牌 及用户信息

      Message({
        message: '登录信息已过期，请重新登录！',
        type: 'error'
      })

      // store.dispatch('asynRemoveToken');
      // store.dispatch('asyndelUserInfo');
      router.replace('/')
    }

    return Promise.reject(error)
  }
)

// 请求 url：port
let baseURL = '/hrm'

/**
 * post 请求接口
 * param: urlPath  域名 + 端口号 + 请求路径
 * param: params json 字符串
 */
export const postAxios = (urlPath, params) => {
  var path = baseURL + urlPath
  return instance({
    method: 'POST',
    url: path,
    data: params
  })
}

export const putAxios = (urlPath, params) => {
  var path = baseURL + urlPath
  return instance({
    method: 'PUT',
    url: path,
    data: params
  })
}

export const deleteAxios = (urlPath) => {
  var path = baseURL + urlPath
  return instance({
    method: 'DELETE',
    url: path
  })
}

export const getAxios = (urlPath) => {
  var path = baseURL + urlPath
  return instance({
    method: 'GET',
    url: path
  })
}

export default instance
